import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

const serverMap = require('../../config/serverMap.js')
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// create an axios instance
const service = axios.create({
  baseURL: serverMap.base, // process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 5000 // 请求超时
})
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code === 0) {
      return res
    } else if (res.code === 2) {
      Message.error(res.message || 'Error')
      return Promise.reject(new Error(res.message || 'Error'))
    } else if (res.code === 1) {
      Message.error(res.message || 'Error')
      return Promise.reject(new Error(res.message || 'Error'))
    } else if (res.code === 3) {
      Message.error(res.message || 'Error')
      return Promise.reject(new Error(res.message || 'Error'))
    } else if (res.code === 7) {
      MessageBox.confirm(
        '登录状态已过期，您可以继续留在该页面，或者重新登录',
        '系统提示',
        {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        location.reload() // 为了重新实例化vue-router对象 避免bug
      })
    }
  },
  error => {
    const res = error.response.data
    if (res.code === 2) {
      Message.error('参数异常,请您耐心等待')
      return Promise.reject(new Error(res.message || 'Error'))
    } else if (res.code === 1) {
      Message.error('系统异常，请刷新页面')
      return Promise.reject(new Error(res.message || 'Error'))
    } else if (res.code === 3) {
      Message.error(res.message || 'Error')
      return Promise.reject(new Error(res.message || 'Error'))
    } else if (res.code === 7) {
      MessageBox.confirm(
        '登录状态已过期，您可以继续留在该页面，或者重新登录',
        '系统提示',
        {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        location.reload() // 为了重新实例化vue-router对象 避免bug
      })
    }
    return Promise.reject(error)
  }
)
export default service
